package com.example.bingobox.dialog;

import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.bingobox.R;
import com.example.bingobox.adapter.LocationMarkRecyclerAdapter;
import com.example.bingobox.adapter.LocationMarkListAdapter;
import com.example.bingobox.model.State;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import android.graphics.Color;
import android.text.SpannableStringBuilder;
import android.text.Spannable;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;

public class LocationTypeManageDialog extends DialogFragment {
    private State state;
    private OnLocationUpdateListener listener;
    private View view;
    private TextView currentLocationText;
    private LocationMarkRecyclerAdapter adapter;
    private State.Location tempLocation;

    public static LocationTypeManageDialog newInstance(State state) {
        LocationTypeManageDialog dialog = new LocationTypeManageDialog();
        dialog.state = state;
        return dialog;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
        LayoutInflater inflater = requireActivity().getLayoutInflater();
        view = inflater.inflate(R.layout.dialog_location_type_manage, null);

        initializeViews(view);
        setupListeners(view);
        setupRecyclerView();
        updateLocationDisplay();

        return builder.setView(view)
                .setTitle("标记地点类型")
                .setPositiveButton("关闭", null)
                .create();
    }

    private void initializeViews(View view) {
        currentLocationText = view.findViewById(R.id.current_location);
    }

    private void setupListeners(View view) {
        view.findViewById(R.id.btn_get_location).setOnClickListener(v -> {
            updateCurrentLocation();
        });

        view.findViewById(R.id.btn_search_location).setOnClickListener(v -> {
            showLocationSearchDialog();
        });
    }

    private void updateLocationDisplay() {
        TextView currentLocationView = view.findViewById(R.id.current_location);
        State.Location location = state.getCurrentLocation();
        
        if (location != null) {
            // 使用 SpannableStringBuilder 来创建两行不同样式的文本
            SpannableStringBuilder builder = new SpannableStringBuilder();
            
            // 添加地址
            String address = location.getAddress() != null ? location.getAddress() : "";
            builder.append(address);
            builder.append("\n");
            
            // 添加名称
            builder.append(location.getName());
            
            // 设置地址为灰色小字
            builder.setSpan(
                new ForegroundColorSpan(Color.GRAY),
                0,
                address.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            );
            builder.setSpan(
                new RelativeSizeSpan(0.8f),
                0,
                address.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            );
            
            currentLocationView.setText(builder);
        } else {
            currentLocationView.setText("");
        }
    }

    private void updateCurrentLocation() {
        try {
            AMapLocationClient.updatePrivacyShow(requireContext(), true, true);
            AMapLocationClient.updatePrivacyAgree(requireContext(), true);
            AMapLocationClient locationClient = new AMapLocationClient(requireContext());
            
            AMapLocationClientOption option = new AMapLocationClientOption();
            option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            option.setOnceLocation(true);
            option.setNeedAddress(true);
            locationClient.setLocationOption(option);

            locationClient.setLocationListener(aMapLocation -> {
                if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                    String locationName;
                    if (aMapLocation.getPoiName() != null && !aMapLocation.getPoiName().isEmpty()) {
                        locationName = aMapLocation.getPoiName();
                    } else if (aMapLocation.getAoiName() != null && !aMapLocation.getAoiName().isEmpty()) {
                        locationName = aMapLocation.getAoiName();
                    } else {
                        locationName = aMapLocation.getStreet() != null ? aMapLocation.getStreet() : "未知位置";
                    }

                    // 构建完整地址
                    StringBuilder addressBuilder = new StringBuilder();
                    if (aMapLocation.getProvince() != null) {
                        addressBuilder.append(aMapLocation.getProvince());
                    }
                    if (aMapLocation.getCity() != null) {
                        addressBuilder.append(aMapLocation.getCity());
                    }
                    if (aMapLocation.getDistrict() != null) {
                        addressBuilder.append(aMapLocation.getDistrict());
                    }
                    if (aMapLocation.getStreet() != null) {
                        addressBuilder.append(aMapLocation.getStreet());
                    }
                    if (aMapLocation.getStreetNum() != null) {
                        addressBuilder.append(aMapLocation.getStreetNum());
                    }

                    // 创建位置对象
                    State.Location location = new State.Location(
                        locationName,
                        aMapLocation.getLatitude(),
                        aMapLocation.getLongitude()
                    );
                    location.setAddress(addressBuilder.toString());

                    // 保存为临时位置
                    tempLocation = location;
                    
                    // 更新显示
                    TextView currentLocationView = view.findViewById(R.id.current_location);
                    SpannableStringBuilder builder = new SpannableStringBuilder();
                    
                    String address = location.getAddress();
                    builder.append(address);
                    builder.append("\n");
                    builder.append(location.getName());
                    
                    builder.setSpan(
                        new ForegroundColorSpan(Color.GRAY),
                        0,
                        address.length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                    );
                    builder.setSpan(
                        new RelativeSizeSpan(0.8f),
                        0,
                        address.length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                    );
                    
                    currentLocationView.setText(builder);

                    // 获取位置成功后，显示类型选择对话框
                    showLocationTypeDialog();
                } else {
                    String errorMessage = aMapLocation != null ? 
                        "错误码: " + aMapLocation.getErrorCode() + ", 错误信息: " + aMapLocation.getErrorInfo() :
                        "获取位置失败";
                    Toast.makeText(getContext(), errorMessage, Toast.LENGTH_SHORT).show();
                }
                locationClient.onDestroy();
            });

            locationClient.startLocation();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "获取位置失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void notifyUpdate() {
        if (listener != null) {
            listener.onLocationUpdated();
        }
    }

    public interface OnLocationUpdateListener {
        void onLocationUpdated();
    }

    public void setOnLocationUpdateListener(OnLocationUpdateListener listener) {
        this.listener = listener;
    }

    private void showLocationSearchDialog() {
        LocationSearchDialog dialog = LocationSearchDialog.newInstance();
        dialog.setOnLocationSelectedListener(location -> {
            TextView currentLocationView = view.findViewById(R.id.current_location);
            
            SpannableStringBuilder builder = new SpannableStringBuilder();
            
            // 添加地址
            String address = location.getAddress() != null ? location.getAddress() : "";
            builder.append(address);
            builder.append("\n");
            
            // 添加名称
            builder.append(location.getName());
            
            // 设置地址为灰色小字
            builder.setSpan(
                new ForegroundColorSpan(Color.GRAY),
                0,
                address.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            );
            builder.setSpan(
                new RelativeSizeSpan(0.8f),
                0,
                address.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            );
            
            currentLocationView.setText(builder);
            
            // 保存临时位置用于标记
            this.tempLocation = location;
            
            showLocationTypeDialog();
        });
        dialog.show(getParentFragmentManager(), "location_search");
    }

    private void showLocationTypeDialog() {
        LocationTypeDialog dialog = LocationTypeDialog.newInstance(state);
        dialog.setOnTypeSelectedListener(type -> {
            try {
                // 使用临时位置而不是当前位置
                State.Location locationToMark = tempLocation != null ? tempLocation : state.getCurrentLocation();
                String currentCityName = state.getCurrentCity().getName();
                
                Map<String, List<State.LocationMark>> cityMarks = state.getCityMarks();
                if (!cityMarks.containsKey(currentCityName)) {
                    cityMarks.put(currentCityName, new ArrayList<>());
                }
                
                State.LocationMark mark = new State.LocationMark(
                    locationToMark,
                    type,
                    state.getCurrentCityType()
                );
                
                cityMarks.get(currentCityName).add(mark);
                
                // 不更新当前位置的类型
                notifyUpdate();
                dismiss();
                
                // 清除临时位置
                tempLocation = null;
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(requireContext(), "添加标记失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        dialog.show(getParentFragmentManager(), "location_type");
    }

    private void setupRecyclerView() {
        RecyclerView recyclerView = view.findViewById(R.id.marked_locations);
        recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        
        // 获取当前城市的标记
        String currentCityName = state.getCurrentCity().getName();
        List<State.LocationMark> marks = state.getCityMarks().get(currentCityName);
        if (marks == null) {
            marks = new ArrayList<>();
        }
        
        LocationMarkListAdapter adapter = new LocationMarkListAdapter(requireContext(), marks);
        recyclerView.setAdapter(adapter);
    }
} 